﻿using Entity.Models;
using HuaRunInterface.Comm;
using HuaRunInterface.Models;
using Microsoft.AspNetCore.Mvc;
using Utility;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace HuaRunInterface.Controllers.AddControllers
{
    [Route("api/HuaRun/[controller]")]
    [ApiController]
    public class AddMeterInfoController : ControllerBase
    {
        // POST api/<AddMeterInfoController>
        [HttpPost]
        public object Post([FromBody] MeterInfo value)
        {
            return AddData(value);
        }

        private object AddData(MeterInfo dto)
        {
            ReturnData rd = new ReturnData();

            try
            {
                string conn = Global.Configuration["ConnectionStrings:DDb"];
                using (Entity.DBContext context = Entity.BaseContext.CreateContext(conn))
                {
                    var v = context.meterInfos.Where(p => p.meterCode == dto.meterCode&&p.IsDelete!=1).FirstOrDefault();
                    if (v != null)
                    {
                        throw new Exception("表具编号不能重复添加！");
                    }
                    dto.sequence = "Meter" + DateTime.Now.ToString("yyyyMMddHHmmssff");
                    dto.meterFactoryCode = Global.Configuration["AppSettings:FactoryCode"];
                    dto.mrFactoryCode = "2000";
                    if (dto.protocolTypeCode != "10100")
                    {
                        dto.mrFactoryCode = Global.Configuration["AppSettings:FactoryCode"];
                    }
                    dto.domainId = Global.DomainId;
                    dto.CreateDate = DateTime.Now;
                    context.meterInfos.Add(dto);

                    string msg = "";
                    MeterRegisterModel model = dto.SerializerObjectToString().JSONStringToObject<MeterRegisterModel>();
                    bool mr = Global.MeterRegister(model, ref msg);
                    if (mr)
                    {
                        context.SaveChanges();
                    }
                    rd.State = mr ? "success" : "failed";
                    rd.Message = msg;
                }
            }
            catch (Exception ex)
            {
                rd.State = "failed";
                rd.Message = ex.Message;
                rd.Data = ex.StackTrace;
            }
            return rd;
        }
    }
}
